package com.huatai.datacenter.service;

import com.huatai.datacenter.entity.ClusterEntity;
import com.huatai.datacenter.mapper.ClusterMapper;
import com.huatai.datacenter.utils.ZKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lion
 * @date 2023/3/24  9:51
 */
@Slf4j
@Service
public class ZKService {


	@Autowired
	private TopicInfoService topicInfoService;

	@Autowired
	private ClusterMapper clusterMapper;

	private Map<String, ZKUtil> cacheZKMap = new HashMap<>(30);

	/**
	 * @author Lion
	 * @description 根据集群id更新
	 * @param  clusterId
	 * @return void
	 */
	public void updateZKAdminByClusterID(String clusterId){
		synchronized (cacheZKMap){
			ClusterEntity cluster = clusterMapper.selectById(clusterId);
			if (cacheZKMap.containsKey(clusterId)){
				cacheZKMap.get(clusterId);
			}
		}
	}

	/**
	 * @author Lion
	 * @description 获取zookeeper信息
	 * @param clusterId
	 * @return com.huatai.datacenter.utils.ZKUtil
	 */
	public ZKUtil getZK(String clusterId) {

		synchronized (cacheZKMap) {
			ClusterEntity cluster = clusterMapper.selectById(clusterId);
			if (!cacheZKMap.containsKey(clusterId)) {
				this.cacheZKMap.put(clusterId, new ZKUtil(cluster.getZkpAddress()));
			}
			return this.cacheZKMap.get(clusterId);
		}
	}

	/**
	 * @author Lion
	 * @description 校验zookeeper连接
	 * @param zkAddress
	 * @return boolean
	 */
	public boolean checkServiceHealth(String zkAddress) {
		boolean flag = false;
		ZKUtil zkUtil = null;
		try {
			zkUtil = new ZKUtil(zkAddress, 1000 * 20, 1000 * 20);
			flag = true;
		} catch (Exception e) {
			log.warn("connect zk error.", e);
		} finally {
			try {
				if (zkUtil != null) {
					zkUtil.close();
				}
			} catch (IOException e) {
			}
		}
		return flag;
	}

}
